package com.choudou5.solr.framework.job;

import com.choudou5.solr.util.LogDeBugUtil;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @name：定时任务工厂
 * @author：choudou5
 * @date：2018-08-05
 */
public class JobFactory {

    private static final Logger logger = LoggerFactory.getLogger(JobFactory.class);

    private static Map<String, JobKey> runJobKeys = new ConcurrentHashMap<>();
    private static Scheduler scheduler = null;

    public static void main(String[] args) throws SchedulerException {
//        startup();
//        String cronExpr = "0/10 * * * * ?";
//        JobFactory.regJob("test", AutoCollectWordJob.class, cronExpr);
    }


    public static void startup() throws SchedulerException{
        logger.info("启动 定时任务服务");
        //Quartz的独立运行容器
        scheduler = new StdSchedulerFactory().getScheduler();
        // 开始
        scheduler.start();
    }
    public static void shutdown() {
        try {
            logger.info("停止 定时任务服务");
            scheduler.shutdown();
        } catch (SchedulerException e) {
            logger.error("停止 定时任务服务失败", e);
        }
    }


    /**
     * 运行 Job
     * @param key
     * @param jobClass
     * @param cronExpr
     * @api: https://blog.csdn.net/kegumingxin2626/article/details/72854823
     * @throws SchedulerException
     */
    public static void regJob(String key, Class jobClass, String cronExpr) throws SchedulerException{
        long begin = System.currentTimeMillis();
        logger.info("runJob key:{};",key);
        if(runJobKeys.containsKey(key)){
            logger.warn("regJob 失败，key:"+key+" 已存在运行的Job");
            return;
        }
        LogDeBugUtil.debug("开始注册Job key:"+key);
        // job 唯一标识
        JobKey jobKey = new JobKey(key , "solr");
        //Quartz在每次执行Job时，都重新创建一个Job实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();
        //描述触发Job执行的时间触发规则
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobKey.toString())
                .startAt(new Date(begin + 1000))  // 延迟一秒执行
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpr))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        runJobKeys.put(key, jobKey);
    }

    /**
     * 停止任务
     * @param key
     * @throws SchedulerException
     */
    public static void stopJob(String key) throws SchedulerException{
        if(!runJobKeys.containsKey(key)){
            logger.warn("stopJob 失败，key:"+key+" 不存在运行的 Job");
            return;
        }
        JobKey jobKey = runJobKeys.get(key);
        // 删除job
        scheduler.deleteJob(jobKey);
        runJobKeys.remove(key);
    }

}
